<?php

namespace Warehouse\Model;

use Inbound\Model\CommoninterfaceModel;
use Think\Model;
use Warehouse\Service\BaseInfoService;
use Warehouse\Service\StockInService;
use Inbound\Service\PublicInfoService;
use Warehouse\Service\PublicdataService;
use Warehouse\Service\StockOutService;


class StockInModel extends CommoninterfaceModel
{
    //入库单对象
    public $warehouseorders = null;
    //质检单
    public $check_quantity = null;

    static $table_ware = 'warehouseorders';

    static $table_storage_sku = 'storage_sku';

    static $table_inventory = 'real_inventories';

    static $table_check = 'check_quality_details';

    static $table_warehouse_deliveryorders = 'warehouse_deliveryorders';

    static $table_shiftrecord = 'shiftrecord';

    /**
     * @param string $table
     * @param array  $param
     */
    public function __construct( $table = '', $param = array() )
    {
        $this->warehouseorders = M( self::$table_ware, 'wms_', $this->_db );
        $this->check_quantity  = M( self::$table_check, 'wms_', $this->_db );
        $this->storage_sku     = M( self::$table_storage_sku, 'wms_', $this->_db );
        $this->storage         = D( 'Warehouse/Storage', 'Model' );
        $this->realinventories = M( self::$table_inventory, 'wms_', $this->_db );
        $this->warehouseDeliveryorders = M( self::$table_warehouse_deliveryorders, 'wms_', $this->_db );
        $this->shiftrecord = M( self::$table_shiftrecord, 'wms_', $this->_db );
        parent::__construct();
    }


    /*
    * 查询入库单
    * */
    public function get_warehouseorders_model_details( &$_array, $flag = false )
    {
        if ( $_array['page'] ) {
            $page = trim( $_array['page'] );
            unset( $_array['page'] );
        }
        if ( $_array['orderby'] ) {
            $orderby = trim( $_array['orderby'] );
            unset( $_array['orderby'] );
        }

        $warehouseorders = $this->get_warehouseorders_model( $_array );

        if ( $flag ) {
            $warehouseorders_count = clone $warehouseorders;    // 进行分页数据查询 注意limit方法的参数要使用Page类的属性

            $this->count = $warehouseorders_count->count();//数量

            $Page = new \Org\Util\Page( $this->count, $page ? $page : 30 );// 实例化分页类 传入总记录数和每页显示的记录数(1)

            $this->page = $Page->show();// 分页显示输出

            $warehouseorders->order( "op_time  ".$orderby )->limit( $Page->firstRow.','.$Page->listRows );
        }

        $result = $warehouseorders->select();

        //echo $warehouseorders->getLastSql();exit;
        $result = StockInService::format_StockIn_details( $result, $flag = true );

        return $result;
    }

    /*
   * 查询入库单
   * */
    public function get_warehouseorders_model_details_sql( &$_array, $flag = false )
    {
        if ( $_array['page'] ) {
            $page = trim( $_array['page'] );
            unset( $_array['page'] );
        }
        if ( $_array['orderby'] ) {
            $orderby = trim( $_array['orderby'] );
            unset( $_array['orderby'] );
        }

        $warehouseorders = $this->get_warehouseorders_model( $_array );
        $result = $warehouseorders->order( "op_time desc" )->select();
        if($flag==true){
            return $result;
        }else{
            return $warehouseorders->getLastSql();
        }
    }

    /**
     * @param array $_array
     *
     * @return mixed
     * 过滤查询条件
     */
    public function get_warehouseorders_model( &$_array = array() )
    {
        if ( $_array ) {
            $_array = array_filter( $_array );
        }
        foreach ( $_array as $key => $_arr ) {
            switch ( $key ) {
                case 'op_time_from':
                    $_array['op_time'][] = array(
                        'EGT', $_arr
                    );
                    unset( $_array['op_time_from'] );
                    break;
                case 'op_time_to':
                    $_array['op_time'][] = array(
                        'ELT', $_arr
                    );
                    unset( $_array['op_time_to'] );
                    break;
            }
            if ( $_array['supplier_id'] ) {
                $_array['supplier_id'] = BaseInfoService::supplier_id( trim( $_array['supplier_id'] ) );
            }
            if ( $_array['warehouse_man'] ) {
                $_array['warehouse_man'] = BaseInfoService::get_user_id( trim( $_array['warehouse_man'] ) );
            }
        }
        return $this->warehouseorders->where( $_array );
    }

    /*
     * 查询入库单
     * */
    public function get_check_quality_details( &$_array, $flag = false )
    {
        $check_quality = $this->get_check_quality_details_model( $_array );

        if ( $flag ) {
            $check_quality_count = clone $check_quality;    // 进行分页数据查询 注意limit方法的参数要使用Page类的属性

            $this->count = $check_quality_count->count();//数量

            $Page = new \Org\Util\Page( $this->count, 25 );// 实例化分页类 传入总记录数和每页显示的记录数(1)

            $this->page = $Page->show();// 分页显示输出

            $check_quality->order( "invoice_date desc" )->limit(1);
        }

        $result = $check_quality->select();
        //echo $check_quality->getLastSql();exit;
        $result = StockInService::check_quality_details( $result, $flag = true );

        return $result;
    }

    /**
     * @param array $_array
     *
     * @return mixed
     * 过滤查询条件
     */
    public function get_check_quality_details_model( &$_array = array() )
    {

        if ( $_array ) {
            $_array = array_filter( $_array );
        }
        foreach ( $_array as $key => $_arr ) {
            switch ( $key ) {
                case 'invoice_date_start':
                    $_array['invoice_date'][] = array(
                        'egt', $_arr
                    );
                    unset( $_array['invoice_date_start'] );
                    break;
                case 'invoice_date_end':
                    $_array['invoice_date'][] = array(
                        'elt', $_arr
                    );
                    unset( $_array['invoice_date_end'] );
                    break;
            }
        }
        if ( $_array['qualified_quantity'] ) {
            $this->check_quantity->where( "`qualified_quantity` >`".$_array['qualified_quantity']."`" );
            unset( $_array['qualified_quantity'] );
        }
        return $this->check_quantity->where( $_array );
    }

    /**
     * 正常质检入库单
     */
    public function batch_create( $_array )
    {
        $this->warehouseorders->startTrans();
        $data  = array();
        $where = array();
        if ( $_array ) {
            foreach ( $_array as $_data ) {
                $_data['warehouseid'] = '102';
                $_data['sku'] = strtoupper(trim($_data['sku']));
                //修改出口退税入库成本的计算方式（如果是出口退税的货就要除以1.17）
                $_data['export_tax_rebate']==1?$_data['cost']=$_data['cost']/1.17:$_data['cost'];
                $_data['sku_name']?$_data['sku_name']:$_data['sku_name']=
                    PublicInfoService::getSkuCnname_bak($_data['sku']);
                $warehouseorders_id   = $this->create( $_data, $this->warehouseorders );
                if ( $warehouseorders_id ) {
                    if ( $_data['type'] == 10 ) {
                        //回写质检入库数量
                        $stockin_num = M( 'check_quality_details', 'wms_', $this->_db )
                            ->where(
                                array(
                                    'id' => $_data['check_quality_detail_id']
                                )
                            )
                            ->getfield( 'stockin_num' );
                        $this->update(
                            array(
                                'id' => $_data['check_quality_detail_id']
                            ),
                            array(
                                'stockin_num' => $_data['warehouse_quantity'] + ( $stockin_num ? $stockin_num : 0 )
                            ),
                            M( 'check_quality_details', 'wms_', $this->_db )
                        );
                        //回写采购单明细的数据
                        $warehouse_quantity = M( 'purchaseorder_details', 'wms_', $this->_db )
                            ->where(
                                array(
                                    'purchaseorder_id' => $_data['purchaseorders_id'],
                                    'sku'              => strtoupper(trim($_data['sku']))
                                )
                            )
                            ->getfield( 'ware_quantity' );
                        $this->update(
                            array(
                                'purchaseorder_id' => $_data['purchaseorders_id'],
                                'sku'              => strtoupper(trim($_data['sku']))
                            ), array(
                            'ware_quantity' => $_data['warehouse_quantity'] + $warehouse_quantity
                        ),
                            M( 'purchaseorder_details', 'wms_', $this->_db )
                        );
                        //回写采购单和明细的状态;
                        $this->update_order_status( $_data, M( 'purchaseorder_details', 'wms_', $this->_db ) );

                        //回写采购明细站点数据表
                        $purchaseOrderDetailsSitesModel = new PurchaseOrderDetailsSitesModel();
                        $sites_map = array(
                            'purchaseorders_id' => $_data['purchaseorders_id'],
                            'sku'               => strtoupper(trim($_data['sku'])),
                            'site_id'           => $_data['site_id'],
                        );
                        $purchaseOrderDetailsSitesModel->setInc_purchaseorder_details_sites($sites_map, array (
                            'column' => 'ware_quantity',
                            'data'   => $_data['warehouse_quantity']
                        ));
                    }

                    $this->warehouseorders->commit();
                    $this->flag  = true;
                    $where['id'] = $warehouseorders_id;
                    $result      = $this->get_warehouseorders_model_details( $where, $flag = true );
                    $data[]      = $result[0];
                } else {
                    $this->flag = false;
                    $this->warehouseorders->rollback();
                }
            }
            return $data;
        }
    }


    /**
     *更新采购单和明细单状态
     * ;65:未完全入库,70:完全入库。
     */
    public function update_order_status( $_array = array(), $model = null )
    {
        $data = $model->field( 'quantity,ware_quantity' )->where(
            array(
                'purchaseorder_id' => $_array['purchaseorders_id'],
                'sku'              => $_array['sku']
            )
        )->find();

        if ( $data ) {
            if ( intval( $data['quantity'] )
                && ( intval( $data['ware_quantity'] ) > 0
                    && intval( $data['ware_quantity'] ) <= intval( $data['quantity'] ) )
            ) {

                if ( intval( $data['quantity'] ) == intval( $data['ware_quantity'] ) ) {
                    $this->update(
                        array(
                            'purchaseorder_id' => $_array['purchaseorders_id'], 'sku' => $_array['sku']
                        ), array( 'status' => '70' ), M( 'purchaseorder_details', 'wms_', $this->_db )
                    );
                    //判断采购单的所有明细是否已经全部入库
                    $status = $model->field( 'status' )->where(
                        array(
                            'purchaseorder_id' => $_array['purchaseorders_id']
                        )
                    )->select();
                    foreach ( $status AS $k => $v ) {
                        if ( intval( $v['status'] ) != '70' ) {
                            return false;
                        }
                    }
                    //完全入库更新采购单状态为70
                    $this->update(
                        array(
                            'id' => $_array['purchaseorders_id']
                        ),
                        array( 'status' => '70' ),
                        M( 'purchaseorders', 'wms_', $this->_db )
                    );
                } else {
                    $this->update(
                        array(
                            'purchaseorder_id' => $_array['purchaseorders_id'], 'sku' => $_array['sku']
                        ),
                        array( 'status' => '65' ),
                        M( 'purchaseorder_details', 'wms_', $this->_db )
                    );
                }
            }
        }
        return true;
    }

    /**
     * 非出口退税
     * 获取当月入库数量
     *
     * @param $sku
     *
     * @return mixed
     */
    public function getSkuWarehouseCount( &$_array )
    {
        $model     = $this->warehouseorders;
        $where_map = array(
            'sku'               => $_array['sku'],
            'enterprise_dominant'   => $_array['enterprise_dominant'],
            'site_id'=> $_array['site_id'],
            'warehouse_date'    => array( 'EGT', date( 'Y-m-01', time() ) ),
            'export_tax_rebate' => 0,
        );

        $res       =
            $model->where( $where_map )->field( 'SUM(warehouse_quantity) AS wo_num, SUM(cost) AS cost' )->find();
        return $res;
    }

    /**
     * 出口退税
     * 获取当月入库数量
     *
     * @param $sku
     *
     * @return mixed
     */
    public function getTaxSkuWarehouseCount( &$_array )
    {
        $model     = $this->warehouseorders;
        $where_map = array(
            'sku'               => $_array['sku'],
            'enterprise_dominant'               => $_array['enterprise_dominant'],
            'site_id'=> $_array['site_id'],
            'warehouse_date'    => array( 'EGT', date( 'Y-m-01', time() ) ),
            'export_tax_rebate' => 1,
        );
        $res       = $model->where( $where_map )->field( 'SUM(warehouse_quantity) AS wo_num, SUM(cost) AS cost' )
            ->find();
        return $res;
    }

    /**
     *更新操作
     */
    public function update_warehouseorders( $_array = array(), $data = array(), &$model = null )
    {
        $model = $model == null ? $this->warehouseorders : $model->table( $this->_db.".wms_".self::$table_ware );
        $res   = $model->where( $_array )->save( $data );
        return $res;
    }


    /**
     * 检查导入数据的有效性
     */
    public function check_warehouse_import_data( $data )
    {
        $flag = true;
        $message = '';
        foreach ($data as $k => $v) {
            if ($k == 1) continue;
            if ($v['A'] == '') {
                $flag = false;
                $message .= '第'.$k.'行sku为空, 导入失败</br>';
            }
            if ( $v['B'] == '' ) {
                $flag = false;
                $message .= '第'.$k.'行储位为空, 导入失败</br>';
            }
        }
        return array(
            'status'  => $flag,
            'message' => $message
        );
    }


    /**
     * 写入入库单
     * 期初库存导入需临时关闭入库单表中的触发器
     */
    public function add_warehouseorders( $data )
    {
        $flag    = false;
        $message = '';
        $failnum = $successnum = 0;

        foreach ( $data as $key => $value ) {
            if ( $key < 2 ) {
                continue;
            }

            //判断sku是否存在
            $sku_count = $this->storage->get_sku_count( array( 'sku' => $value['A'] ) );
            if ( $sku_count <= 0 ) {
                $failnum++;
                $message .= '第'.$key.'行sku【'.$value['A'].'】不存在,导入失败!</br>';
                continue;
            }

            //判断储位是否存在
            $storage = $this->storage->get_storage_by_where( array( 'storage_position' => $value['B'] ) );
            if ( !$storage ) {
                $failnum++;
                $message .= '第'.$key.'行储位【'.$value['B'].'】不存在,导入失败！</br>';
                continue;
            }

            $export_tax_rebate = trim($value['D']) == '出口退税' ? 1 : 0;
            $warehouse_data['warehouseid'] = $inventory_data['warehouseid'] = 102;
            $warehouse_data['sku'] = $inventory_data['sku'] = $value['A'];
            $warehouse_data['storage_position'] = $value['B'];
            $warehouse_data['warehouse_quantity'] = $inventory_data['quantity'] = $value['C'];
            $warehouse_data['available_quantity'] = $value['C'];
            $warehouse_data['export_tax_rebate'] = $inventory_data['export_tax_rebate'] = $export_tax_rebate;
            $warehouse_data['remark'] = $value['E'];
            $warehouse_data['type'] = 30;  //盘赢
            $warehouse_data['warehouse_date'] = date('Y-m-d');
            $warehouse_data['op_time'] = date('Y-m-d H:i:s');

            //插入入库单表
            $this->warehouseorders->add($warehouse_data);

            //插入实时库存表，如果已经有此sku，则其实际库存数量累加，没有就插入
            $where = array('warehouseid' => 102, 'sku' => $value['A'], 'export_tax_rebate' => $export_tax_rebate);
            $inventory = $this->realinventories->where($where)->count();
            if ($inventory) {
                $this->realinventories->where($where)->setInc('quantity', $value['C']);
            } else {
                $this->realinventories->add($inventory_data);
            }

            $flag = true;
            $successnum ++;
        }

        $message .= '成功导入'.$successnum.'条数据！失败'.$failnum.'条！';

        return array(
            'flag'    => $flag,
            'message' => $message
        );
    }


    /**
     * 查询sku在每个储位的可用库存
     * 如果只传其中一个参数,其他的参数请用''占用
     *
     * @param array $storage_postion
     * @param array $skus
     *
     * @return mixed
     */
    public function get_storage_inventories( $storage_postion, $skus ,$enterprise_dominant ,$site_id,$export_tax_rebate)
    {
        $model = $this->warehouseorders;
        if ( !empty( $storage_postion ) ) {
            $storage_postion = is_array( $storage_postion ) ? $storage_postion : array( $storage_postion );
        }
        if ( !empty( $skus ) ) {
            $skus = is_array( $skus ) ? $skus : array( $skus );
        }
        $where_map = array(
            'enterprise_dominant'=>$enterprise_dominant,
            'site_id'=>$site_id,
            'export_tax_rebate'=>$export_tax_rebate
        );
        $where_map = array_filter($where_map);
        if($export_tax_rebate==='0'){
            $where_map['export_tax_rebate']  = 0;
        }

        if ($skus){
            $where_map['sku']  = array('in',$skus);
        }
        if ($storage_postion){
            $where_map['storage_position']  = array('in', $storage_postion);
        }
        $where_map['available_quantity']  = array( 'GT', 0 );

        return $model->where( $where_map )->group( 'sku, storage_position, export_tax_rebate, enterprise_dominant,site_id' )
            ->field(
                'site_id, sku, sku_name, export_tax_rebate, enterprise_dominant, storage_position, SUM(available_quantity) AS all_available_quantity'
            );
    }

    /**
     * @return mixed
     * 获取入库单所有sku可用库存
     */
    public function get_all_storage_inventories(){
        return $this->warehouseorders->group( 'sku, storage_position, export_tax_rebate, enterprise_dominant,site_id' )
            ->where(array('available_quantity'=>array( 'GT', 0 )))
            ->field(
                'site_id, sku, sku_name, export_tax_rebate, enterprise_dominant, storage_position, SUM(available_quantity) AS all_available_quantity'
            )
            ->select();
    }


    /**
     * 根据条件获取入库单
     */
    public function get_storage_warehouse_orders($where, $field = '*') {
        $result = $this->warehouseorders->field($field)->where($where)->order('op_time asc')->select();
        return $result;
    }


    /**
     * 储位移位
     */
    public function storage_move($data) {
        $this->stockOut = D('StockOut', 'Service');

        $flag = false;

        //移入的储位出口退税值
        $export_tax_rebate = $this->storage->get_storage_by_where(array('storage_position' => $data['to_storage']));
        $export_tax_rebate = $export_tax_rebate ? $export_tax_rebate['export_tax_rebate'] : 0;

        //选中的站点储位创建出库单
        $deliveryordersIds = array();
        foreach ($data['check'] as $k => $v) {
            $checkData = json_decode($v, true);
            $stockOutData = array(
                'site_id'            => $checkData['site_id'],
                'storage_position'   => $checkData['storage_position'],
                'sku'                => $data['sku'],
                'sku_name'           => PublicInfoService::getSkuCnname_bak($data['sku']),
                'sku_standard'       => PublicdataService::get_sku_standard($data['sku']),
                'quantity'           => $data['available_quantity'][$k],
                'enterprise_dominant'=> $checkData['enterprise_dominant'],
                'export_tax_rebate'  => $checkData['export_tax_rebate'],
                'type'               => 130, //移位出库
                'remark'             => ''
            );

            $resultDelivery = $this->stockOut->create_formate($stockOutData, false);
            if (!isset($resultDelivery[0]['error']) || $resultDelivery[0]['error'] != 0) {
                return false;
            }

            array_push($deliveryordersIds, $resultDelivery[0]['deliveryorders_id']);
        }

        if (!$deliveryordersIds) {
            return false;
        }

        //到达储位创建入库单
        $deliveryorders = $this->warehouseDeliveryorders->where(array('deliveryorders_id' => array('IN', $deliveryordersIds)))->select();
        $warehouseOrderIds = i_array_column($deliveryorders, 'warehouseorders_id');
        if (!$warehouseOrderIds) {
            return false;
        }

        $field = 'id, purchaseorders_id, batch_code, returned_parcel_id, check_quality_detail_id, unqualified_deal_invoice_id, deliveryorders_id, supplier_id, department,  
                sku, storage_position, site_id, tax_way, remark, warehouse_man, store, enterprise_dominant, transfer_hopper_id, transfer_type, single_price, cost, transportation_expense, money, tax_price';
        $warehouseOrderOld = $this->get_storage_warehouse_orders(array('id' => array('in', $warehouseOrderIds)), $field);
        foreach ($warehouseOrderOld as $key => $val) {
            foreach ($val as $k => $v) {
                $warehouseOrderData[$k] = $v;
            }

            //待写入入库单的数据
            $warehouseOrderData['warehouse_date']        = date('Y-m-d');
            $warehouseOrderData['op_time']               = date('Y-m-d H:i:s');
            $warehouseOrderData['sku']                   = $data['sku'];
            $warehouseOrderData['sku_name']              = PublicInfoService::getSkuCnname_bak($data['sku']);
            $warehouseOrderData['sku_standard']          = PublicdataService::get_sku_standard($data['sku']);
            $warehouseOrderData['storage_position']      = $data['to_storage'];
            $warehouseOrderData['pre_warehouseorder_id'] = $val['id'];
            $warehouseOrderData['warehouse_quantity']    = $deliveryorders[$key]['quantity'];
            $warehouseOrderData['available_quantity']    = $deliveryorders[$key]['quantity'];
            $warehouseOrderData['site_id']               = $val['site_id'];
            $warehouseOrderData['money']                 = $val['single_price'] * $deliveryorders[$key]['quantity'];
            $warehouseOrderData['type']                  = 130;   //移位入库
            $warehouseOrderData['export_tax_rebate']     = $export_tax_rebate;

            unset($warehouseOrderData['id']);
            $warehouseInsertData[] = $warehouseOrderData;

            //待写入库存移位记录表的数据
            $shiftRecordData['warehouseid']           = 102;
            $shiftRecordData['from_storage_position'] = $val['storage_position'];
            $shiftRecordData['sku']                   = $val['sku'];
            $shiftRecordData['quantity']              = $deliveryorders[$key]['quantity'];
            $shiftRecordData['to_storage_position']   = $data['to_storage'];
            $shiftRecordData['adder_id']              = session('current_account.id');
            $shiftRecordData['create_time']           = date('Y-m-d H:i:s');

            $shiftRecordInsertData[] = $shiftRecordData;
        }

        //移位成功
        if ($this->batch_create($warehouseInsertData)) {
            //写入库存移位记录表
            $this->shiftrecord->addAll($shiftRecordInsertData);

            //判断sku与目标储位是否绑定，如果未绑定，则自动绑定
            $storage_sku = $this->storage_sku->where(array('storage_position' => $data['to_storage'], 'sku' => $data['sku']))->find();
            if (!$storage_sku) {
                $bindData = array(
                    'storage_position' => $data['to_storage'],
                    'sku' => $data['sku'],
                    'export_tax_rebate' => $export_tax_rebate
                );
                $this->storage_sku->add($bindData);
            }

            $flag = true;
        }

        return $flag;
    }

    public function checkCode () {
        $deliveryordersIds=array('136729102','136728102');
        $data['sku'] = 'AM71703';
        $data['to_storage'] = 'AAA5787';
        $export_tax_rebate= 0;
        $deliveryorders = $this->warehouseDeliveryorders->where(array('deliveryorders_id' => array('IN', $deliveryordersIds)))->select();
        $warehouseOrderIds = i_array_column($deliveryorders, 'warehouseorders_id');
        if (!$warehouseOrderIds) {
            return false;
        }

        $field = 'id, purchaseorders_id, batch_code, returned_parcel_id, check_quality_detail_id, unqualified_deal_invoice_id, deliveryorders_id, supplier_id, department,  
                sku, storage_position, site_id, tax_way, remark, warehouse_man, store, enterprise_dominant, transfer_hopper_id, transfer_type, single_price, cost, transportation_expense, money, tax_price';
        $warehouseOrderOld = $this->get_storage_warehouse_orders(array('id' => array('in', $warehouseOrderIds)), $field);
        foreach ($warehouseOrderOld as $key => $val) {
            foreach ($val as $k => $v) {
                $warehouseOrderData[$k] = $v;
            }

            //待写入入库单的数据
            $warehouseOrderData['warehouse_date']        = date('Y-m-d');
            $warehouseOrderData['op_time']               = date('Y-m-d H:i:s');
            $warehouseOrderData['sku']                   = $data['sku'];
            $warehouseOrderData['sku_name']              = PublicInfoService::getSkuCnname_bak($data['sku']);
            $warehouseOrderData['sku_standard']          = PublicdataService::get_sku_standard($data['sku']);
            $warehouseOrderData['storage_position']      = $data['to_storage'];
            $warehouseOrderData['pre_warehouseorder_id'] = $val['id'];
            $warehouseOrderData['warehouse_quantity']    = $deliveryorders[$key]['quantity'];
            $warehouseOrderData['available_quantity']    = $deliveryorders[$key]['quantity'];
            $warehouseOrderData['site_id']               = $val['site_id'];
            $warehouseOrderData['money']                 = $val['single_price'] * $deliveryorders[$key]['quantity'];
            $warehouseOrderData['type']                  = 130;   //移位入库
            $warehouseOrderData['export_tax_rebate']     = $export_tax_rebate;

            unset($warehouseOrderData['id']);
            $warehouseInsertData[] = $warehouseOrderData;

            //待写入库存移位记录表的数据
            $shiftRecordData['warehouseid']           = 102;
            $shiftRecordData['from_storage_position'] = $val['storage_position'];
            $shiftRecordData['sku']                   = $val['sku'];
            $shiftRecordData['quantity']              = $deliveryorders[$key]['quantity'];
            $shiftRecordData['to_storage_position']   = $data['to_storage'];
            $shiftRecordData['adder_id']              = session('current_account.id');
            $shiftRecordData['create_time']           = date('Y-m-d H:i:s');

            $shiftRecordInsertData[] = $shiftRecordData;
        }

        //移位成功
        if ($this->batch_create($warehouseInsertData)) {

            //判断sku与目标储位是否绑定，如果未绑定，则自动绑定
            $this->shiftrecord->addAll($shiftRecordInsertData);

            //判断sku与目标储位是否绑定，如果未绑定，则自动绑定
            $storage_sku = $this->storage_sku->where(array('storage_position' => $data['to_storage'], 'sku' => $data['sku']))->find();
            if (!$storage_sku) {
                $bindData = array(
                    'storage_position' => $data['to_storage'],
                    'sku' => $data['sku'],
                    'export_tax_rebate' => $export_tax_rebate
                );
                $this->storage_sku->add($bindData);
            }
            echo '移位成功';
        } else {
            echo '移位失败';
        }
        exit;
    }

    /**
     * @param $data
     * @return bool
     * 站点调拨
     */
    public function site_move($data) {

        $this->stockOut = D('Warehouse/StockOut', 'Service');

        $flag = false;
        //选中的站点创建出库单
        $deliveryordersIds = array();
        $stockInData = array();
        $sites    = array_flip(PublicInfoService::get_site_array());
        $sku_name = PublicInfoService::getSkuCnname_bak($data['sku']);
        $sku_standard = PublicdataService::get_sku_standard($data['sku']);

        foreach ($data['site'] as $k=>$s) {
            $stockOutData = array(
                'site_id'            => $sites[$s],
                'sku'                => $data['sku'],
                'sku_name'           => $sku_name,
                'sku_standard'       => $sku_standard,
                'storage_position'   => $data['storage_position'][$k],
                'quantity'           => $data['available_quantity'][$k],
                'enterprise_dominant'=> $data['enterprise_dominant'][$k],
                'export_tax_rebate'  => $data['export_tax_rebate'][$k],
                'type'               => 150, //站点调拨
                'remark'             => ''
            );
            $resultDelivery = $this->stockOut->create_formate($stockOutData,false);

            if (!isset($resultDelivery[0]['error']) || $resultDelivery[0]['error'] != 0) {
                return false;
            }

            array_push($deliveryordersIds, $resultDelivery[0]['deliveryorders_id']);

            if (!$deliveryordersIds) {
                return false;
            }
        }                                                                                          //end foreach
        //到达储位创建入库单
        $deliveryorders = $this->warehouseDeliveryorders                             //入库出库关联关系表查出数据
        ->where(array('deliveryorders_id' => array('IN', $deliveryordersIds)))
            ->select();
        $warehouseOrderIds = i_array_column($deliveryorders, 'warehouseorders_id');
        if (!$warehouseOrderIds) {
            return false;
        }
        $field = 'id, purchaseorders_id, batch_code, returned_parcel_id, check_quality_detail_id, 
                unqualified_deal_invoice_id, deliveryorders_id, supplier_id, department,export_tax_rebate, 
                sku, storage_position, tax_way, remark, warehouse_man, store, enterprise_dominant, 
                transfer_hopper_id, transfer_type, single_price, cost, transportation_expense, money, tax_price';
        $warehouseOrderOld = $this
            ->get_storage_warehouse_orders(array('id' => array('in', $warehouseOrderIds)), $field);//查询原入库单信息
        foreach ($warehouseOrderOld as $key => $val) {
            foreach ($val as $k => $v) {
                $warehouseOrderData[$k] = $v;
            }
            //待写入入库单的数据
            $warehouseOrderData['warehouse_date'] = date('Y-m-d H:i:s');
            $warehouseOrderData['op_time'] = date('Y-m-d H:i:s');
            $warehouseOrderData['sku'] = $data['sku'];
            $warehouseOrderData['sku_name'] = $sku_name;
            $warehouseOrderData['sku_standard'] = $sku_standard;
            $warehouseOrderData['pre_warehouseorder_id'] = $val['id'];
            $warehouseOrderData['warehouse_quantity'] = $deliveryorders[$key]['quantity'];     //取入库出库关系表的数量
            $warehouseOrderData['available_quantity'] = $deliveryorders[$key]['quantity'];
            $warehouseOrderData['site_id'] = $data['site_id'];
            $warehouseOrderData['money']
                = $warehouseOrderData['single_price']*$deliveryorders[$key]['quantity'];
            $warehouseOrderData['type'] = 150;                                                 //站点调拨

            unset($warehouseOrderData['id']);
            $stockInData[] = $warehouseOrderData;
        }
        $st = $this->batch_create($stockInData);                                                   //移位成功
        if ($st) {
            $flag = true;
        }

        return $flag;
    }

    /**
     * 获取移动sku总数量
     */
    private function get_sum_quantity($data) {
        $sum = 0;
        foreach ($data['storage'] as $key => $value) {
            $sum += $data['available_quantity'][$value];
        }
        return $sum;
    }
    /**
     * @return mixed
     * 获取入库单指定月sku可用库存
     * khq 2017.4.28
     */
    public function get_qichu_in(){
        $starttime = date('Y-m-01', strtotime('-1 month'));
        $endtime   = date('Y-m-t', strtotime('-1 month'));
        $where['warehouse_date'][] = array('EGT',$starttime);
        $where['warehouse_date'][] = array('ELT',$endtime.' 23:59:59');
        return $this->warehouseorders->group( 'sku,enterprise_dominant,export_tax_rebate,site_id')
            ->where($where)
            ->where(array('type'=>array( 'eq', 10 )))
            ->field(
                'sku,enterprise_dominant,export_tax_rebate,site_id,sku_name,sku_standard,supplier_id,
                SUM(warehouse_quantity) AS all_quantity,SUM(cost) AS all_cost'
            )
            ->select();
    }

    /**
     * 描述：根据SKU、主体、入库类型获取当月入库成本
     * 作者：橙子
     */
    public function get_month_in($where) {
        $_where = array();

        $starttime = date('Y-m-01', strtotime('-1 month'));
        $endtime   = date('Y-m-t', strtotime('-1 month'));

        if ($where['warehouse_date']) {
            $starttime = date('Y-m-01', strtotime($where['warehouse_date']));
            $endtime   = date('Y-m-t', strtotime($where['warehouse_date']));

        }

        $_where['warehouse_date'][] = array('EGT', $starttime);
        $_where['warehouse_date'][] = array('ELT', $endtime.' 23:59:59');
        $where['sku'] && $_where['sku'] = $where['sku'];
        $where['enterprise_dominant'] && $_where['enterprise_dominant'] = $where['enterprise_dominant'];

        $result = $this->warehouseorders->field('sku,enterprise_dominant,sku_name,
        SUM(warehouse_quantity) AS totalQuantity,SUM(cost) AS totalCost,type')
            ->group('sku,enterprise_dominant,type')
            ->where($_where)
            ->select();

        return empty($result) ? array() : $result;
    }

    /**
     * 描述：下个期初的上个月入库数据
     * 作者：橙子
     */
    public function crontab_month_in($where) {
        $_where = array();

        $starttime = date('Y-m-01', strtotime('-1 month'));
        $endtime   = date('Y-m-t', strtotime('-1 month'));

        $_where['warehouse_date'][] = array('EGT', $starttime);
        $_where['warehouse_date'][] = array('ELT', $endtime.' 23:59:59');

        $result = $this->warehouseorders->field('sku,enterprise_dominant,sku_name,
        SUM(warehouse_quantity) AS totalQuantity,SUM(cost) AS totalCost')
            ->group('sku,enterprise_dominant')
            ->where($_where)
            ->select();

        return empty($result) ? array() : $result;
    }

    /**
     * 描述：获取入库成本为0的数据
     * 作者：橙子
     */
    public function get_cost_zero_value($month) {
        $starttime = date('Y-m-01', strtotime($month));
        $endtime   = date('Y-m-t', strtotime($month));
        $where['warehouse_date'][] = array('EGT', $starttime);
        $where['warehouse_date'][] = array('ELT', $endtime.' 23:59:59');

        return $this->warehouseorders->where($where)
            ->where(array('cost' => array('EQ', 0)))
            ->field('id,warehouse_date,sku,enterprise_dominant,warehouse_quantity,type,cost')
            ->select();
    }

    /**
     * 描述：更新入库成本为0的数据
     * 作者：橙子
     */
    public function save_cost($array) {
        $this->warehouseorders->startTrans();
        $update_flag = TRUE;

        foreach ($array as $_array) {
            $_where['id'] = $_array['A'];
            $_data['cost'] = $_array['G'];

            $result = $this->warehouseorders->where($_where)->save($_data);
            if ($result === FALSE) {
                $update_flag = FALSE;
                break;
            }
        }

        if ($update_flag) {
            $this->warehouseorders->commit();
            $message = '成本已经更新！';
        } else {
            $this->warehouseorders->rollback();
            $message = "成本更新出错，请重试！";
        }

        return $message;
    }

    /**
     * 描述：检查SKU是否有无采购单入库
     * 作者：橙子
     */
    public function checkWarehouseOrder($array) {
        $array['available_quantity'] = array('GT', 0);
        $array['purchaseorders_id'] = array('EQ', 0);

        return $this->warehouseorders->where($array)
            ->field('id')
            ->limit(1)
            ->select();
    }

}